﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.IO;
using System.Reflection;
//using PSE.ProcessManager.Common.Logging;
using System.Configuration;
using PSE.Framework.ErrorLogging;
using PSE.ProcessManager.Common.Process;
using PSE.Framework.Process;
using PSE.Framework.Configuration;

namespace PSE.ProcessManager.Server.InteligenceManagerInstance
{
    class Program : BaseProgram
    {
        static Program()
        {
            Initialize(PSE.Framework.Configuration.Components.SystemComponents.System, PSE.Framework.Configuration.Components.SystemComponents.ProcessManagerInstance);
        }

        private const string CONFIGFILENAME = ConfigurationManager.ConfigurationManager.INTELIGENCE_MANAGER_INSTANCE_CONFIG;
        private static InteligenceManager _inteligenceManager;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            //while (!System.Diagnostics.Debugger.IsAttached)
            //    System.Threading.Thread.Sleep(1000);

            try
            {
                string productName, instanceName;

                productName = args[0].Split('_')[0];
                instanceName = args[0].Split('_')[1];

                //Implementacao para tornar MULTI-PRODUTO
                //Criar um appDomain para subir a instancia do executor, possibilitando dessa forma informar um config especifico para cada
                //produto/instancia 
                string instanceConfigFile = Path.GetDirectoryName(System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath) + @"\Instances\" + productName + @"\" + instanceName + @"\" + CONFIGFILENAME;

                if (!File.Exists(instanceConfigFile))
                    throw new FileNotFoundException("The config file could not be found", instanceConfigFile);

                AppDomainSetup domainSetup = new AppDomainSetup();
                domainSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                domainSetup.ApplicationName = AppDomain.CurrentDomain.SetupInformation.ApplicationName;
                domainSetup.ConfigurationFile = instanceConfigFile;

                AppDomain executorDomain = AppDomain.CreateDomain("Product:" + productName + " Instance:" + instanceName, null, domainSetup);

                _inteligenceManager = (InteligenceManager)executorDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "PSE.ProcessManager.Server.InteligenceManagerInstance.InteligenceManager");

                if (!_inteligenceManager.Initialize(args))
                    return;
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                if (_inteligenceManager != null)
                {
                    _inteligenceManager.Dispose();
                    _inteligenceManager = null;
                }
            }
        }
    }
}
